package com.younge.spring.component.config;

import com.younge.spring.api.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public CommonResult<String> handleException(Exception e) {
        log.error(Arrays.toString(e.getStackTrace()));
        return CommonResult.error(e.getLocalizedMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> handleValidationException(MethodArgumentNotValidException e) {
        log.error(e.getLocalizedMessage());
        String msg = e.getBindingResult().getFieldError().getDefaultMessage();
        return CommonResult.error(msg);
    }
}
